package org.bioversityinternational.mgbms.ws.security;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class IpRangeFilter implements Filter {
	
	private List<String> m_allowedIPs;

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain fc) throws IOException, ServletException {
		if (!m_allowedIPs.isEmpty() && !m_allowedIPs.contains(request.getRemoteAddr()))
			throw new ServletException("You are not allowed to access this service!");
		
		fc.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		String allowedIPs = filterConfig.getInitParameter("allowedIPs");
		m_allowedIPs = Arrays.asList(allowedIPs.length() == 0 ? new String[0] : allowedIPs.split(","));
	}

}
